package org.dromara.common.websocket.config;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.dromara.common.websocket.config.properties.WebSocketProperties;
import org.dromara.common.websocket.handler.BoardWebSocketHandler;
import org.dromara.common.websocket.interceptor.BoardWebSocketInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * WebSocket 配置
 *
 * @author zendwang
 */
@AutoConfiguration
@ConditionalOnProperty(value = "websocket.enabled", havingValue = "true")
@EnableConfigurationProperties(WebSocketProperties.class)
@EnableWebSocket
public class BoardWebSocketConfig {
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Bean
    public WebSocketConfigurer boardWebSocketConfigurer(HandshakeInterceptor boardHandshakeInterceptor,
                                                        WebSocketHandler boardWebSocketHandler,
                                                        WebSocketProperties webSocketProperties) {
        if (StrUtil.isBlank(webSocketProperties.getAllowedOrigins())) {
            webSocketProperties.setAllowedOrigins("*");
        }

        return registry -> registry
                .addHandler(boardWebSocketHandler, webSocketProperties.getBoardPath())
                .addInterceptors(boardHandshakeInterceptor)
                .setAllowedOrigins(webSocketProperties.getAllowedOrigins());
    }

    @Bean
    public HandshakeInterceptor boardHandshakeInterceptor() {
        return new BoardWebSocketInterceptor();
    }

    @Bean
    public WebSocketHandler boardWebSocketHandler() {
        return new BoardWebSocketHandler(applicationEventPublisher);
    }
}
